﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Catalog.API.Infrastructure;
using CatalogApi;
using Grpc.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using static CatalogApi.Catalog;

namespace Catalog.API.Grpc
{
    public class CatalogService : CatalogBase
    {
        private readonly ILogger<CatalogService> _logger;
        private readonly CatalogContext _catalogContext;

        public CatalogService(ILogger<CatalogService> logger,
            CatalogContext context)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _catalogContext = context ?? throw new ArgumentNullException(nameof(context));
        }
        public override async Task<ExpressStoreDataResponse> GetExpressStoresByCode(ExpressStoreRequest request, ServerCallContext context)
        {
            var storeCodes = request.ExpressStoreCodes.Select(t => t);
            var expressStores = await _catalogContext.ExpressStores.Where(t => storeCodes.Contains(t.ExpressStoreCode)).ToListAsync();
            ExpressStoreDataResponse response = new ExpressStoreDataResponse();
            foreach(var item in expressStores)
            {
                response.Data.Add(new ExpressStoreResponse
                {
                    ContactMan = item.ContactMan,
                    ExpressStoreCode = item.ExpressStoreCode,
                    Name = item.Name,
                    OwnerId = item.OwnerId,
                    Phone = item.Phone,
                    Status = item.Status
                });
            }
            return response;
        }
        public override async Task<ProductDataResponse> GetProductsByCode(ProductRequest request, ServerCallContext context)
        {
            var products = await _catalogContext.Products.Where(t => request.ProductCodes.Contains(t.ProductCode)).ToListAsync();
            ProductDataResponse response = new ProductDataResponse();
            foreach (var item in products)
            {
                response.Data.Add(new ProductResponse
                {
                    ProductCode = item.ProductCode,
                    ProductType = item.ProductType,
                    Name = item.Name,
                    Description = item.Description,
                    Remark = item.Remark,
                    Size = item.Size,
                    Price = (double)item.Price
                });
            }
            return response;
        }

    }
}
